package com.cloud.clouddemo.controller;

import com.cloud.clouddemo.pojo.User;
import io.micrometer.core.instrument.MeterRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: xben
 * @Date: 2018/12/19 10:28
 */
@RestController
public class HelloController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MeterRegistry meterRegistry; //actuator相关
    @Autowired
    Registration registration; //服务注册
    @Autowired
    private DiscoveryClient client; //服务发现客户端

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() throws InterruptedException {
        ServiceInstance instance = serviceInstance();
        //让线程沉睡几秒,
//		int sleepTime = new Random().nextInt(3000);
//		Thread.sleep(sleepTime);
//		logger.info("线程睡了几秒"+sleepTime);
        logger.info("你好,host是   " + instance.getHost() + "service_id:是" + instance.getServiceId());
        return "Hello World";
    }

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    public String hello(@RequestParam String name) {
        return "Hello " + name;
    }

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public User hello(@RequestHeader String name, @RequestHeader Integer age) {
        return new User(name, age);
    }

    @RequestMapping(value = "/hello3", method = RequestMethod.POST)
    public String hello(@RequestBody User user) {
        return "Hello " + user.getName() + user.getAge();
    }

    public ServiceInstance serviceInstance() {
        //根据服务ID获取当前服务实例
        List<ServiceInstance> list = client.getInstances(registration.getServiceId());
        if (list != null && !list.isEmpty()) {
            for (ServiceInstance instance : list) {
                return list.get(0);
            }
        }
        return null;
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(@RequestParam String name) {
        return "你的名字叫 " + name;
    }
}
